import { useEffect } from "react";
import { Spin, Space, Divider, Empty, message, Popconfirm } from "antd";
import { Card as SemiCard, Row, Col, List, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconDelete } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import dayjs from "dayjs";

import GatewayCard from "../components/gateway.card";

const GatewayOrganizations = () => {
    const { remoteData, windowInnerHeight } = useModel("global");

    const state = useReactive({
        loading: false,
        fileLoading: false,
        submitLoading: false,
        services: [],
        logFiles: [],
        logFileContent: "",
        selectedGateway: {},
        selectedService: {},
        selectedLogFile: "",
        isDeleteLogFile: false,
    });

    const loadServices = async () => {
        state.loading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            p2pNodeUuid: state.selectedGateway.uuid,
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/v1/services/getAll",
            params: {},
        });
        state.services = res?.filter((item) => item.serviceType === "api") || [];
        state.loading = false;
    };

    useEffect(() => {
        state.selectedGateway?.url && loadServices();
    }, [state.selectedGateway]);

    const loadLogFiles = async () => {
        state.loading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            p2pNodeUuid: state.selectedGateway.uuid,
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/" + state.selectedService.serviceName,
            params: { apiPath: "/logs/getFiles", data: {} },
        });
        state.logFiles = res || [];
        state.selectedLogFile = "";
        state.logFileContent = "";
        state.loading = false;
    };

    useEffect(() => {
        state.selectedService?.serviceHost && loadLogFiles();
    }, [state.selectedService]);

    const handleSelectedGateway = async (gateway) => {
        state.selectedGateway = gateway;
    };

    const getLogFileContent = async () => {
        let logDate = state.selectedLogFile.filename.split(".").at(-1);
        state.isDeleteLogFile = dayjs(logDate).isValid();
        state.fileLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            p2pNodeUuid: state.selectedGateway.uuid,
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/" + state.selectedService.serviceName,
            params: { apiPath: "/logs/getLogsContent", data: { filename: state.selectedLogFile.filename } },
        });
        state.logFileContent = res?.content || "";
        state.fileLoading = false;
    };

    useEffect(() => {
        if (state.selectedLogFile?.filename) {
            getLogFileContent();
        } else {
            state.logFileContent = "";
        }
    }, [state.selectedLogFile]);

    const deleteLogfile = async () => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            p2pNodeUuid: state.selectedGateway.uuid,
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/" + state.selectedService.serviceName,
            params: { apiPath: "/logs/deleteLogsFile", data: { filename: state.selectedLogFile.filename } },
        });
        if (res) {
            message.success("成功删除日志文件");
            state.logFileContent = "";
            loadLogFiles();
        }
        state.submitLoading = false;
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={5}>
                    <GatewayCard cardBodyHeight={cardBodyHeight} handleSelectedGateway={handleSelectedGateway} />
                </Col>
                <Col span={5}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>服务列表</span>}
                        headerExtraContent={<Space split={<Divider type="vertical" />} size={4}></Space>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 1, height: cardBodyHeight - 2, overflow: "auto" }}
                    >
                        <List
                            loading={state.loading}
                            dataSource={state.services}
                            renderItem={(item, index) => (
                                <List.Item
                                    key={index}
                                    className={`list-item ${state.selectedService?.serviceUuid === item?.serviceUuid ? "list-selected-item" : ""}`}
                                    main={<div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.serviceName || "-"}</div>}
                                    onClick={() => (state.selectedService = item)}
                                ></List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={5}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>日志文件列表</span>}
                        headerExtraContent={<Space split={<Divider type="vertical" />} size={4}></Space>}
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 1, height: cardBodyHeight - 2, overflow: "auto" }}
                    >
                        <List
                            loading={state.loading}
                            dataSource={state.logFiles}
                            renderItem={(item, index) => (
                                <List.Item
                                    key={index}
                                    className={`list-item ${state.selectedLogFile?.filename === item?.filename ? "list-selected-item" : ""}`}
                                    main={<div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.filename || "-"}</div>}
                                    extra={helper.byteConvert(item.size)}
                                    onClick={() => (state.selectedLogFile = item)}
                                ></List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={9}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>日志文件内容</span>}
                        headerExtraContent={
                            <ButtonGroup>
                                {state.isDeleteLogFile && state.logFileContent && (
                                    <Popconfirm placement="topRight" title="确认要删除该日志文件吗?" okButtonProps={{ loading: state.submitLoading }} onConfirm={deleteLogfile}>
                                        <Button icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                                    </Popconfirm>
                                )}
                            </ButtonGroup>
                        }
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight - 2 }}
                    >
                        <pre className="log-file-pre" style={{ padding: "10px 30px", height: cardBodyHeight - 20 }}>
                            <Spin spinning={state.fileLoading}>{state.logFileContent ? state.logFileContent : <Empty />}</Spin>
                        </pre>
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

export default GatewayOrganizations;
